﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace IdComLog.Validation
{
    /// <summary>
    /// Validates that a string is a US ZIP code, formatted as either XXXXX or XXXXX-XXXX.
    /// </summary>
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false)]
    public class ZipCodeAttribute : ValidationAttribute
    {
        public ZipCodeAttribute()
            : base("Field {0} must be a zip code in format XXXXX or XXXXX-XXXX.")
        {
        }

        public override bool IsValid(object value)
        {
            string s = value as string;
            return string.IsNullOrEmpty(s) || re.IsMatch(s);
        }

        static readonly Regex re = new Regex(@"\d{5}(?:(?:-|‒)\d{4})?", RegexOptions.Compiled);
    }
}
